import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { HttpExceptionFilter } from './core/filter/http-exception.filter';
import { TransformInterceptor } from './core/interceptor/transform.interceptor'
//swagger
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';



const net = require('net');
const desiredPort = process.env.LISTEN || 3000;

function portInUse(port) {
  return new Promise((resolve, reject) => {
    const server = net.createServer().listen(port, () => {
      server.close();
      resolve(false);
    }).on('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        resolve(true);
      } else {
        reject(err);
      }
    });
  })
}

async function findAvailablePort(startPort) {
  let port = startPort;
  while (await portInUse(port)) {
    port++;
  }
  return port;
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api/v1');  //全局路由前缀
  app.useGlobalPipes(new ValidationPipe());  //全局验证管道
  app.useGlobalFilters(new HttpExceptionFilter()); //全局异常过滤器
  app.useGlobalInterceptors(new TransformInterceptor()); //全局接口返回拦截器

  const config = new DocumentBuilder()
    .setTitle('后台管理系统接口')
    .setDescription('后台管理系统的一次尝试')
    .setVersion('1.0')
    .addTag('后台')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  findAvailablePort(desiredPort)
    .then(async (availablePort) => {
      console.log(`端口${desiredPort}可能被占用，已找到可用端口：${availablePort}`);
      await app.listen(availablePort);
    }).catch(error => {
      console.error('查找可用端口时发生错误:', error);
    });
}
bootstrap();
